//
//  RoundState.cpp
//  DiceWar
//
//  Created by xiaofeng on 22/6/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#include "WarLayerState.h"
#include "GameMaster.h"
#include "WarLayer.h"
#include "Player.h"

void WarLayerStateWaitForAttacker::onHexCellClicked(int coordinateX, int coordinateY, WarLayer& controller)
{
    PlayerType player = controller.m_playersManager.getCurrentPlayer();
    
    const HexMapGrid& grid = GameMaster::instance().getHexMap().getMapGrid(coordinateX, coordinateY);
    if (!grid.isOwnedByPlayer(player)) return;
    
    controller.m_pFightingLayer->setAttacker(coordinateX, coordinateY);
    controller.m_state.changeToWaitForDefender();
}

void WarLayerStateWaitForAttacker::onFightingAnimOver(WarLayer& controller)
{
    return;
}

void WarLayerStateWaitForDefender::onHexCellClicked(int coordinateX, int coordinateY, WarLayer& controller)
{
    PlayerType player = controller.m_playersManager.getCurrentPlayer();
    const HexMapGrid& grid = GameMaster::instance().getHexMap().getMapGrid(coordinateX, coordinateY);
    if (!grid.isPlayable()) return;

    if (grid.isOwnedByPlayer(player))
    {
        controller.m_pFightingLayer->setAttacker(coordinateX, coordinateY);
        return;
    }
    
    if (!controller.m_pFightingLayer->isNextToAttacker(coordinateX, coordinateY)) return;
    
    controller.m_pFightingLayer->setDefender(coordinateX, coordinateY);
    controller.startFightAnimation();
}

void WarLayerStateWaitForDefender::onFightingAnimOver(WarLayer& controller)
{
    controller.m_pFightingLayer->unsetAttacker();
    controller.m_pFightingLayer->unsetDefender();
    controller.m_state.changeToWaitForAttacker();
}

WarLayerState::WarLayerState()
: m_pState(NULL) {}

WarLayerState::~WarLayerState() {}

void WarLayerState::changeToWaitForAttacker()
{
    m_pState = &m_waitForAttackerState;
}

void WarLayerState::changeToWaitForDefender()
{
    m_pState = &m_waitForDefenderState;
}

void WarLayerState::onHexCellClicked(int coordinateX, int coordinateY, WarLayer& controller)
{
    if (m_pState) m_pState->onHexCellClicked(coordinateX, coordinateY, controller);
}

void WarLayerState::onFightingAnimOver(WarLayer& controller)
{
    if (m_pState) m_pState->onFightingAnimOver(controller);
}
